# -*- coding: utf-8 -*-
# @Time    : 2019/2/28 18:28
# @Author  : z.t.b
# @Email   : zhtbin@163.com
# @File    : addTwoNumbers.py
# @Software: PyCharm

"""
给出两个 非空 的链表用来表示两个非负的整数。其中，它们各自的位数是按照 逆序 的方式存储的，并且它们的每个节点只能存储 一位 数字。

如果，我们将这两个数相加起来，则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外，这两个数都不会以 0 开头。

示例：

输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出：7 -> 0 -> 8
原因：342 + 465 = 807
"""
import json


class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution(object):
    def addTwoNumbers(self, ln1, ln2):
        result = ListNode(0)
        node1 = ln1
        node2 = ln2
        current = result
        carry = 0
        while node1 or node2:
            x = node1.val if node1 else 0
            y = node2.val if node2 else 0
            sum = carry + x + y
            carry = sum // 10
            current.next = ListNode(sum % 10)
            current = current.next
            if node1 : node1 = node1.next
            if node2 : node2 = node2.next
        if carry > 0: current.next = ListNode(1)
        return result.next


def stringToIntegerList(input):
    return json.loads(input)


def stringToListNode(input):
    # Generate list from the input
    numbers = stringToIntegerList(input)

    # Now convert that list into linked list
    dummyRoot = ListNode(0)
    ptr = dummyRoot
    for number in numbers:
        ptr.next = ListNode(number)
        ptr = ptr.next

    ptr = dummyRoot.next
    return ptr


def listNodeToString(node):
    if not node:
        return "[]"

    result = ""
    while node:
        result += str(node.val) + ", "
        node = node.next
    return "[" + result[:-2] + "]"

def printListNode(node):
    nodeList = node
    while(nodeList):
        print(nodeList.val,end="->")
        nodeList = nodeList.next

solution = Solution()

node1 = stringToListNode("[2,4,3]")
node2 = stringToListNode("[5,6,4]")
result = solution.addTwoNumbers(node1, node2)
print(listNodeToString(result))
# printListNode(solution.addTwoNumbers(node1, node2))


